package cn.com.anysdk.redis.factory;

import cn.com.anysdk.redis.api.IRedisService;
import cn.com.anysdk.redis.exception.RedisException;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Redis 服务代理工厂
 */
@Slf4j
public class RedisServiceProxyFactory {
    /**
     * 创建 Redis 服务代理
     * @param service 原始 Redis 服务
     * @return 代理后的 Redis 服务
     */
    public static IRedisService createProxy(IRedisService service) {
        return (IRedisService) Proxy.newProxyInstance(
                service.getClass().getClassLoader(),
                new Class<?>[]{IRedisService.class},
                new RedisServiceInvocationHandler(service)
        );
    }

    private static class RedisServiceInvocationHandler implements InvocationHandler {
        private final IRedisService target;

        public RedisServiceInvocationHandler(IRedisService target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            try {
                return method.invoke(target, args);
            } catch (Exception e) {
                Throwable cause = e.getCause();
                if (cause instanceof RedisException) {
                    throw cause;
                } else {
                    throw new RedisException("Redis operation failed: " + e.getMessage(), e);
                }
            }
        }
    }
} 